package com.ruoyi.project.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.domainenum.FinSubjectDirectionType;
import com.ruoyi.common.domainenum.FinSubjectMoneyType;
import com.ruoyi.common.domainenum.FinSubjectStatus;
import com.ruoyi.common.domainenum.FinSubjectType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.project.common.StaticMethod;
import com.ruoyi.project.domain.FinCurrency;
import com.ruoyi.project.domain.FinPackage;
import com.ruoyi.project.domain.FinSubject;
import com.ruoyi.project.mapper.FinCurrencyMapper;
import com.ruoyi.project.mapper.FinSubjectMapper;
import com.ruoyi.project.service.IBootstrapService;
import com.ruoyi.project.service.IFinSubjectMonthService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.*;

@Service
public class BootstrapServiceImpl implements IBootstrapService {
    private static Logger logger = LoggerFactory.getLogger(BootstrapServiceImpl.class.getName());

    private final String subjectDataFile="init-data/all.json";

    @Resource
    private FinSubjectMapper finSubjectMapper;
    @Resource
    private FinCurrencyMapper finCurrencyMapper;
    @Resource
    private IFinSubjectMonthService finSubjectMonthService;
    Integer total = 0;

    @Override
    @Transactional
    public void initData(FinPackage finPackage) throws IOException {
        InputStream inputStream = Thread.currentThread()
                .getContextClassLoader()
                .getResourceAsStream(subjectDataFile);
        String content = readFile(inputStream);
        List<FinSubject> finSubjectList = JSON.parseArray(content,FinSubject.class);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(finPackage.getStartTime());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        total = 0;
        finSubjectList.forEach(finSubject -> {
            insertFinSubject(finSubject,finPackage,null,year,month);
            if(finSubject.getChildren()!=null && !finSubject.getChildren().isEmpty()){
                finSubject.getChildren().forEach(childSub->{
                    insertFinSubject(childSub,finPackage,finSubject,year,month);
                    if(childSub.getChildren()!=null && !childSub.getChildren().isEmpty()){
                        childSub.getChildren().forEach(childSubSub->{
                            insertFinSubject(childSubSub,finPackage,childSub,year,month);
                        });
                    }
                });
            }
        });
        FinCurrency finCurrency = new FinCurrency();
        StaticMethod.setCreateField(finCurrency, SecurityUtils.getUserId(),SecurityUtils.getUsername());
        finCurrency.setPackageId(finPackage.getId());
        finCurrency.setCode("RMB");
        finCurrency.setName("人民币");
        finCurrency.setExchangeRate(new BigDecimal(1.0));
        finCurrency.setHasBase(true);
        finCurrencyMapper.insert(finCurrency);
        logger.info("finSubject total-->{}",total);
    }

    private void insertFinSubject(FinSubject finSubject,FinPackage finPackage,FinSubject parent,int year,int month){
        finSubject.setPackageId(finPackage.getId());
        if(parent!=null){
            finSubject.setParentId(parent.getId());
            finSubject.setParentName(parent.getName());
            finSubject.setParentCode(parent.getCode());
            finSubject.setSubjectLevel(parent.getSubjectLevel()+1);
        }else{
            finSubject.setSubjectLevel(1);
        }
        finSubject.setId(null);
        finSubject.setHasDefault(true);
        StaticMethod.setCreateField(finSubject,SecurityUtils.getUserId(),SecurityUtils.getUsername());
        finSubjectMapper.insert(finSubject);
        finSubjectMonthService.createBySubject(finSubject,year,month);
        total++;
    }


    private String readFile(InputStream inputStream) throws IOException {

        StringBuilder builder = new StringBuilder();
        try {
            InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bfReader = new BufferedReader(reader);
            String tmpContent = null;
            while ((tmpContent = bfReader.readLine()) != null) {
                builder.append(tmpContent);
            }
            bfReader.close();
        } catch (UnsupportedEncodingException e) {
            // 忽略
            e.printStackTrace();
        }
        return builder.toString();
    }

    public static void main(String args[]) throws IOException {

        String jsonStr = FileUtils.readFileToString(new File("D:\\work\\sxkj\\ruoyi-project\\src\\main\\resources\\init-data\\1.json"), Charset.forName("UTF8"));
        JSONArray subjectArray = JSON.parseArray(jsonStr);
        for(int i=2;i<=5;i++){
            jsonStr = FileUtils.readFileToString(new File("D:\\work\\sxkj\\ruoyi-project\\src\\main\\resources\\init-data\\"+i+".json")
                    , Charset.forName("UTF8"));
            subjectArray.addAll( JSON.parseArray(jsonStr));
        }
        List<FinSubject> finSubjectList = new ArrayList<>(subjectArray.size());
        Map<Long,FinSubject> finSubjectMap = new HashMap<>();
        for(int i=0;i<subjectArray.size();i++){
            JSONObject obj = subjectArray.getJSONObject(i);
            FinSubject finSubject = new FinSubject();
            finSubject.setStatus(FinSubjectStatus.ONLINE);
            finSubject.setCode(obj.getString("id"));
            finSubject.setId(obj.getLong("id"));
            finSubject.setName(obj.getString("name"));
            if(obj.getString("yefx").equals("1")){
                finSubject.setDirectionType(FinSubjectDirectionType.JIE);
            }else{
                finSubject.setDirectionType(FinSubjectDirectionType.DAI);
            }
            finSubject.setPinYinFirst(obj.getString("fpy"));
            finSubject.setParentId(obj.getLongValue("pid"));
            switch (obj.getString("sx")){
                case "01":
                    finSubject.setSubjectType(FinSubjectType.ZC);
                    break;
                case "02":
                    finSubject.setSubjectType(FinSubjectType.FZ);
                    break;
                case "03":
                    finSubject.setSubjectType(FinSubjectType.QY);
                    break;
                case "04":
                    finSubject.setSubjectType(FinSubjectType.CB);
                    break;
                case "05":
                    finSubject.setSubjectType(FinSubjectType.SY);
                    break;
                default:
                    break;
            }
            switch (obj.getString("xjkm")){
                case "0":
                    finSubject.setMoneyType(FinSubjectMoneyType.NOT_MONEY);
                    break;
                case "1":
                    finSubject.setMoneyType(FinSubjectMoneyType.MONEY);
                    break;
                case "2":
                    finSubject.setMoneyType(FinSubjectMoneyType.BANK);
                    break;
                case "3":
                    finSubject.setMoneyType(FinSubjectMoneyType.MONEY_EQUAL);
                    break;
                default:
                    break;
            }
            finSubjectMap.put(finSubject.getId(),finSubject);
            if(finSubject.getParentId()>0){
                FinSubject parentSubject = finSubjectMap.get(finSubject.getParentId());
                finSubject.setParentName(parentSubject.getName());
                if(parentSubject.getChildren()==null){
                    parentSubject.setChildren(new ArrayList<>());
                }
                parentSubject.getChildren().add(finSubject);
            }else{
                finSubjectList.add(finSubject);
            }
        }
        FileUtils.writeStringToFile(new File("D:\\work\\sxkj\\ruoyi-project\\src\\main\\resources\\init-data\\all.json"),JSON.toJSONString(finSubjectList));
    }
}
